#!/usr/bin/env python2
#coding:utf-8
import sys
import getopt
import random
import urllib2
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.proxy import Proxy
from selenium.webdriver.common.proxy import ProxyType

def get_tel_loc(s):
	url = "https://www.baidu.com/s?wd=" +s+"&tn=84053098_3_dg&ie=utf-8"
	browser = webdriver.PhantomJS()
	proxy=webdriver.Proxy()
	proxy.proxyType=ProxyType.MANUAL
	proxy.httpProxy=get_porxy()
	proxy.add_to_capabilities(webdriver.DesiredCapabilities.PHANTOMJS)
	browser.get(url)
	element_List = browser.find_elements_by_xpath("/html/body/div/div[3]/div[1]/div[3]/div[1]/div[1]/div/div[2]/div[1]/span[2]")
	if len(element_List) == 1:
		print s, element_List[0].text
	# print(dl,browser.page_source)
	browser.quit()

def get_porxy():
	zhima_url = "http://webapi.http.zhimacangku.com/getip?xxxxxx"
	response = urllib2.urlopen(zhima_url)
	return str.strip(response.read())

def help():
	print("\n使用方法1:\n\npython main.py --end=15510200000 --start=15510000000")
	print("\n使用方法2:\n\npython main.py --no=15510200000")
	
if __name__ == '__main__':
	try:
		opts, args = getopt.getopt(sys.argv[1:], "hp:i:", ["help", "start=", "end=","no="])
	except getopt.GetoptError:
		print "参数错误"
		help()
		sys.exit()
	no = ''
	start = ''
	end = ''
	for option, value in opts:
		if option in ("-h", "--help"):
			help()
		if option in ("-s", "--start"):
			if len(value) != 11:
				sys.exit("start参数长度有误")
			start = value
		if option in ("-e", "--end"):
			if len(value) != 11:
				sys.exit("end参数长度有误")
			end = value
		if option in ("--no"):
			if len(value) != 11:
				sys.exit("no参数长度有误")
			no = value

	if len(no) == 11:
		print '获取'+no+'归属地'
		get_tel_loc(no)
		sys.exit()

	if len(start) == 11 and len(end) == 11:
		if start[0:3] != end[0:3]:
			sys.exit("号段必须一致")
		if int(start[3:7]) > int(end[3:7]):
			sys.exit("开始号段必须大于结束号段")
		print "开始号段扫描 " + start[0:7] +"-"+ end[0:7]
		for num in range(int(start[3:7]),int(end[3:7])):
			get_tel_loc(start[0:3] + bytes(num) + "0000")
			# time.sleep(2)
		sys.exit()

	help() 